//
//  XWWeChatOpenSDKBridgeProtocolImpl.swift
//  XWWeChatOpenSDKBridge
//
//  Created by xianquan on 2024/4/10.
//

import CommonTools
import WechatOpenSDK


let universalLink = "https://app.jichacha.vip/app/"

class XWWeChatOpenSDKBridgeProtocolImpl: NSObject {
    
    static let shared = XWWeChatOpenSDKBridgeProtocolImpl()
    
    private override init(){}

    var authSuccessCallback: (String) -> () = {_ in}
}

extension XWWeChatOpenSDKBridgeProtocolImpl {
    /// 是否安装微信
    var isWXAppInstalled: Bool {
        WXApi.isWXAppInstalled()
    }
    
    func startLog(logBlock: @escaping (String) -> ()) {
        WXApi.startLog(by: .detail) { log in
            logBlock(log)
        }
    }
    
    func registerApp() {
        let isRegister =  WXApi.registerApp(wxAppId, universalLink: universalLink)
        print("微信SDK注册\(isRegister)")
//        checkUniversalLinkReady()
    }
    
    func checkUniversalLinkReady(){
        #if DEBUG
        WXApi.checkUniversalLinkReady { step, result in
            var type = ""
            switch step {
            case .params:
                type = "参数检查"
            case .systemVersion:
                type = "当前系统版本检查"
            case .wechatVersion:
                type = "微信客户端版本检查"
            case .sdkInnerOperation:
                type = "微信SDK内部操作检查"
            case .launchWechat:
                type = "App拉起微信检查"
            case .backToCurrentApp:
                type = "由微信返回当前App检查"
            case .final:
                type = "最终检查"
            @unknown default:
                break
            }
            print("step: \(type),\(result.success ? "成功" : "失败"), errorInfo: \(result.errorInfo), suggestion: \(result.suggestion)")
        }
        #endif
    }
    
    func handleOpen(url: URL) -> Bool{
        WXApi.handleOpen(url, delegate: self)
    }
    
    func handleOpenUniversalLink(userActivity: NSUserActivity) -> Bool {
        WXApi.handleOpenUniversalLink(userActivity, delegate: self)
    }
    
    func sendAuthReq(viewController: UIViewController, success: @escaping (String) -> ()) {
        authSuccessCallback = success
        let req = SendAuthReq()
        req.scope = "snsapi_userinfo"
        req.openID = wxAppId
//        req.nonautomatic = true
        WXApi.sendAuthReq(req, viewController: viewController, delegate: self)
    }
    
    func sendShareReq(image: UIImage? = nil, title: String? = nil, description: String? = nil) {
        let req = SendMessageToWXReq()
        let sharedImage = image ?? UIImage(named: "share_image")
        let imageObj = WXImageObject()
        if let imageData = sharedImage?.jpegData(compressionQuality: 1.0 ) {
            imageObj.imageData = imageData
        }
        let message = WXMediaMessage()
        message.mediaObject = imageObj
        if let title = title {
            message.title = title
        }
        if let description = description {
            message.description = description
        }
        
        req.message = message
        req.scene = Int32(WXSceneSession.rawValue)
        WXApi.send(req)
    }
}


extension XWWeChatOpenSDKBridgeProtocolImpl: WXApiDelegate {
    func onReq(_ req: BaseReq) {
        
        if let wxReq = req as? SendAuthReq {
            print("WechatUtil.onReq ==== SendAuthReq \(wxReq)")
        } else if let wxReq = req as? SendMessageToWXReq {
            print("WechatUtil.onReq ==== SendMessageToWXReq \(wxReq)")
        } else if let wxReq = req as? GetMessageFromWXReq {
            print("WechatUtil.onReq ==== GetMessageFromWXReq \(wxReq)")
        } else if let wxReq = req as? ShowMessageFromWXReq {
            print("WechatUtil.onReq ==== ShowMessageFromWXReq \(wxReq)")
        } else if let wxReq = req as? LaunchFromWXReq {
            print("WechatUtil.onReq ==== LaunchFromWXReq \(wxReq)")
        } else {
            print("WechatUtil.onReq ==== \(req)")
        }
    }
    
    func onResp(_ resp: BaseResp) {
        if let wxResp = resp as? SendAuthResp {
            print("WechatUtil.onResp ==== SendAuthResp \(wxResp)")
            // ERR_OK = 0(用户同意) ERR_AUTH_DENIED = -4（用户拒绝授权） ERR_USER_CANCEL = -2（用户取消）
            print("WechatUtil.onResp ==== SendAuthResp \(wxResp.errCode)")
            // 用户换取 access_token 的 code，仅在 ErrCode 为 0 时有效
            print("WechatUtil.onResp ==== SendAuthResp \(wxResp.code ?? "")")
            if wxResp.errCode == 0 {
                authSuccessCallback(wxResp.code ?? "")
            }
        } else if let wxResp = resp as? SendMessageToWXResp {
            print("WechatUtil.onResp ==== SendMessageToWXResp \(wxResp)")
        } else if let wxResp = resp as? GetMessageFromWXResp {
            print("WechatUtil.onResp ==== GetMessageFromWXResp \(wxResp)")
        } else if let wxResp = resp as? ShowMessageFromWXResp {
            print("WechatUtil.onResp ==== ShowMessageFromWXResp \(wxResp)")
        } else {
            print("WechatUtil.onResp ==== \(resp)")
        }
    }
}
